package com.yulong.web.server.Impl;


import com.rabbitmq.http.client.domain.UserInfo;
import com.yulong.model.pojo.UmsAdmin;
import com.yulong.model.pojo.UmsAdminRoleRelation;
import com.yulong.model.pojo.UmsPermission;
import com.yulong.web.mapper.UmsAdminMapper;
import com.yulong.web.mapper.UmsAdminRoleRelationMapper;
import com.yulong.web.server.UmsAdminService;
import com.yulong.web.utils.JwtTokenUtil;
import com.yulong.web.utils.ResponseMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UmsAdminServerImpl implements UmsAdminService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServerImpl.class);
    private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private UmsAdminMapper umsAdminMapper ;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UmsAdminRoleRelationMapper umsAdminRoleRelationMapper;


    @Override
    public List<UserInfo> selectAll() {
        List<UserInfo> userInfos = umsAdminMapper.selectAll();
        return userInfos;
    }

    @Override
    public List<UmsAdmin> selectList(String username) {
        return umsAdminMapper.selectList(username);
    }

    @Override
    public ResponseMap register(UmsAdmin umsAdmin) {

        //查询是否有相同的用户，
        UmsAdmin umsAdmin1 = umsAdminMapper.queryByUserName(umsAdmin.getUsername());
        if(umsAdmin1!=null){
            return  ResponseMap.errorMsg("用户已存在");
        }
        //将密码加密
        String password = passwordEncoder.encode(umsAdmin.getPassword());
        UmsAdmin user = new UmsAdmin();
        user.setCreateTime(new Date());
        user.setLoginTime(new Date());
        user.setUsername(umsAdmin.getUsername());
        user.setPassword(password);
        user.setEmail(umsAdmin.getEmail());
        user.setIcon(umsAdmin.getIcon());
        user.setNickName(umsAdmin.getNickName());
        user.setNote(umsAdmin.getNote());
        user.setStatus(0);
        int i = umsAdminMapper.register(user);
        return ResponseMap.ok(i);
    }

    @Override
    public ResponseMap login(String username,String password) {

        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            System.out.println(userDetails);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);

        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }

        return ResponseMap.build(200,"成功",token);


    }

    @Override
    public UmsAdmin queryByUserName(String username) {
        UmsAdmin umsAdmin = umsAdminMapper.queryByUserName(username);
        return umsAdmin ;
    }

    @Override
    public ResponseMap deleteById(String id) {
        int i = umsAdminMapper.deleteById(id);
        return ResponseMap.ok(i);
    }

    @Override
    public ResponseMap updateById(UmsAdmin umsAdmin) {
        umsAdmin.setPassword( passwordEncoder.encode(umsAdmin.getPassword()));
        int i = umsAdminMapper.updateById(umsAdmin);
        return ResponseMap.ok(i);
    }

    @Override
    @Transactional
    public ResponseMap updateRole(Long adminId, List<Integer> roleIds) {
        //查询已经绑定的关系 ，删除掉再插入
        List<UmsAdminRoleRelation> umsAdminRoleRelations = umsAdminMapper.queryByAdminId(adminId);
        if(umsAdminRoleRelations!=null){
            List<Long> ids = new ArrayList<>();
            for(UmsAdminRoleRelation item  : umsAdminRoleRelations){
                Long id = item.getId();
                ids.add(id);
            }

            int i = umsAdminMapper.deleteRoleByAdminId(ids);

        }
        int i = umsAdminMapper.updateRole(adminId, roleIds);
        return ResponseMap.ok(i);
    }

    /**
     * 查询用户的角色表
     *
     * @param adminId
     * @return
     */
    @Override
    public ResponseMap queryAdminRoleRelationList(Long adminId) {
        List<UmsAdminRoleRelation> umsAdminRoleRelations = umsAdminRoleRelationMapper.queryAdminRoleRelationList(adminId);

        return ResponseMap.ok(umsAdminRoleRelations);
    }

    /**
     * 禁用启用用户
     *
     * @param id
     * @param status 0  禁用  1  启用
     * @return
     */
    @Override
    public ResponseMap updateByStatus(Long id, Long status) {
        int i = umsAdminMapper.updateByStatus(id, status);
        return ResponseMap.ok(i);
    }

    @Override
    public List<UmsPermission> getPermissionList(Long adminId) {
        List<UmsPermission> permissionList = umsAdminRoleRelationMapper.getPermissionList(adminId);

        return permissionList;
    }


    public UmsAdminServerImpl() {
        super();
    }
}
